package com.bw.test;


import com.sun.org.apache.bcel.internal.generic.FMUL;

import javax.rmi.CORBA.Util;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.Random;

public class Date8Utiles {
    public static void main(String[] args) {


//        System.out.println( Date8Utiles.addDay("2021-03-26",10));
//        System.out.println(getLastDayofMonth("2020-02-02",false));
//        System.out.println(getFormarDat(LocalDate.now(),"yyyy-MM-dd"));
//        System.out.println(getAge("1963-03-24"));
        System.out.println(randomDateTime("2021-02-02","2021-03-03"));
    }

     static DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    //获取指定范围的随机时间
    public static String randomDateTime(String startDay,String endDay){
        LocalDate parse = LocalDate.parse(startDay);
        LocalDate end = LocalDate.parse(endDay);
        long between = ChronoUnit.DAYS.between(parse, end);
        Random random = new Random();
        LocalDate minus = end.minus(random.nextInt((int) between), ChronoUnit.DAYS);
        return fmt.format(minus);
    }
    //根据生日获取年龄
    public static Integer getAge(String birthday){
        LocalDate date = LocalDate.parse(birthday, DateTimeFormatter.ISO_DATE);
        Long until = date.until(LocalDate.now(), ChronoUnit.YEARS);
        return until.intValue();
    }
    //获取一个人性化日期
    public static String getFormarDat(LocalDate date,String format){
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern(format);
        return sdf.format(date);
    }
    //获取指定日期的月初ttrue
    //获取指定日期的月末false
    public static String getLastDayofMonth(String curDate,boolean firstOrLast){
       if(firstOrLast){
           return LocalDate.parse(curDate,DateTimeFormatter.ofPattern("yyyy-MM-dd")).with(TemporalAdjusters.firstDayOfMonth()).toString();
       }else{
           return LocalDate.parse(curDate,DateTimeFormatter.ofPattern("yyyy-MM-dd")).with(TemporalAdjusters.lastDayOfMonth()).toString();
       }
    }
    //用指定日期加减天数
    public static String addDay(String date,int day){
        LocalDate start = LocalDate.parse(date);
        LocalDate minus = start.minus(-day, ChronoUnit.DAYS);
        return fmt.format(minus);
    }

}
